//repack.js
const app = getApp();
var level = require('../../utils/level.js');//导入等级数据列表
var config = require('../../utils/parts');//导入配件公式信息
var requestUrl = getApp().request("url");
var header = getApp().request("header");

Page({
    data: {
        hasOneCar: true,//拥有一辆车
        hasTwoCar: false,//拥有两辆车
        hasThreeCar: false,//拥有三辆车
        choseCar: 1,//当前选择车辆
        chance: 0,//当日剩余抽奖机会
        lastTime: '12：12',//抽奖等待时间
        hasChance: true,//当前是否可以抽奖
        canPlay: true,//当日是否还能抽奖
        levelIntroShow: false,//等级说明弹窗
        levelItem: level.list,//等级信息列表
        score: 0,//用户评分
        // isfirst: "",//是否第一次进改装车间
        // second_guide:"page-guide",//指引页地址
        // changeGuide_count: 0,//我知道了按钮次数
        baseImgUrl: config.imgUrl,//图片地址
        //==============================================================================
        //配件图片路径部分
        imgUrl_g: '',
        imgUrl_c: '',
        imgUrl_b: '',
        imgUrl_f: '',
        imgUrl_a: '',
        imgUrl_e: '',
        imgUrl_d: '',
        //==============================================================================
        //插槽图片路径
        chacao_f:'',
        chacao_c:'',
        chacao_b:'',
        chacao_g:'',
        chacao_a:'',
        chacao_e:'',
        chacao_d:'',
        chacao_h:'',
        //==============================================================================        
        carRank: '',
        carLevel: '',
        carName: '',
        carArrName: 0,
        parts: {
            a: false,
            b: false,
            c: false,
            d: false,
            e: false,
            f: false,
            g: false,
            h: false
        },//拥有高级配件时显示红点
        carNum: 1//用户已有车数量
    },
    onLoad: function () {
       
    },
    onShow: function () {
      
      wx.showShareMenu({
        withShareTicket: true
      });
        var _this = this;
        var fightCarTypeId = app.globalData.fightCarTypeId,
          goldcoin = app.globalData.gold,
          score = app.globalData.score,
          carArrName = Number(app.globalData.carName),
          drawLeftN = app.globalData.drawLeftN,
          car = app.globalData.car,
          depot = app.globalData.depot;
         
        if (_this.data.fightCarTypeId == 0) return;
        if (_this.data.hasCar === false && fightCarTypeId != 0) {
            _this.setData({
                hasCar: true
            })
        }
        _this.setData({
            goldcoin: goldcoin,
            score: score,
            carArrName: carArrName,
            chance:drawLeftN,
            car:car,
            depot:depot,
            carName: "SUV概念车"
        })
        _this.doScoreAnalysis(score);
        _this.doChacaoImgUrl();
        _this.doMainImgUrl();
        _this.doRedPoint();
    },
    onShareAppMessage:function(){
      var that = this;
      //是否选车
      var fightCarTypeId = app.globalData.fightCarTypeId;
      //随机一句宣言
      var declaration = getApp().Refit();
      var myRefitTxt = Math.floor(Math.random() * declaration.length);
      
      if (fightCarTypeId == 0) {
        return {
          title: getApp().shareTitle1(),
          path: "/pages/index/index"
        }
      } else {
        return {
          title: getApp().shareTitle2(),
          path: "/pages/openShare/openShare?shareId=" + app.globalData.session_key.userId + "&carTypeId=" + fightCarTypeId + "&shareRefitNum=" + myRefitTxt + "&carName=SUV概念车",
          success: (re) => {
            if (Object.keys(re).length == 1) {
              return
            }
            var ticket = re.shareTickets[0];
            wx.getShareInfo({
              shareTicket: ticket,
              success: function (Re) {
                console.log(Re)
                var encryptedData = Re.encryptedData;
                var iv = Re.iv;
                //请求分享接口加次数
                wx.showLoading({
                  title: '',
                  mask:true
                });
                wx.request({
                  url: requestUrl + 'shareGroupAddDrawNum',
                  method: "POST",
                  data: { userId: app.globalData.session_key.userId, salt: app.globalData.session_key.salt, encryptedData: encryptedData, iv: iv },
                  header: header,
                  success: function (Res) {
                    console.log(Res);
                    wx.hideLoading();
                    if (Res.data.code == 200) {
                      //当日剩余抽取次数减去一
                      var shareLeftN = app.globalData.shareLeftN;
                      shareLeftN--;
                      app.globalData.shareLeftN = shareLeftN;
                      //剩余抽取次数加3次
                      var drawLeftN = app.globalData.drawLeftN;
                      drawLeftN += 3;
                      app.globalData.drawLeftN= drawLeftN;
                      //页面分享进度减一
                      that.setData({
                        chance: that.data.chance + 3
                      })

                    } else if (Res.data.code == 401 || Res.data.code == 301 || Res.data.code == 302) {
                      getApp().showModal("提交信息有误!")
                    } else if (Res.data.code == 304) {
                      //getApp().showModal("解密错误!")
                      getApp().sessionKey()
                    } else if (Res.data.code == 800) {
                      getApp().showModal(Res.data.data.msg);
                      wx.hideLoading();
                    }
                  },
                  fail: function (res) {
                    console.log("分享加次数接口fail");
                    console.log(res);
                    wx.hideLoading();
                    getApp().showModal("网络错误，请重试");
                  }
                })
              }
            })
          }
        }
      }
    },
    onReady:function(){
        
    },
    doRedPoint(){
        //处理红点
        var _this = this;
        var has_depot = _this.data.depot,
            _thisCar = _this.data.car,
            red_point_obj = {};

        for(var key in has_depot){
            if(has_depot[key] != 0){
                if(_thisCar[0][key[0]] == ''){
                    red_point_obj[key[0]] = true;
                }else{

                    var depot_parts_score = _this.getScore(key),
                        car_parts_score = _this.getScore(_thisCar[0][key[0]]);

                    if(depot_parts_score > car_parts_score){
                        red_point_obj[key[0]] = true
                    }
                }
            }
        }
        _this.setData({
            parts:red_point_obj
        })
    },
    doChacaoImgUrl:function(){
        var _this = this;
        var arr = ['a','b','c','d','e','f','g','h'],
            resArr = [];
        for(var i = 0; i < arr.length; i++){
            if(_this.data.car[0][arr[i]] == ''){
                resArr.push(_this.data.baseImgUrl + '/' + 'parts-' + arr[i] + '.png');
            }else{
                var str = _this.data.car[0][arr[i]],
                    str0 = _this.data.car[0][arr[i]][0];

                resArr.push(_this.data.baseImgUrl + '/parts/' + str[0] + '/' + str + '_small.png');
            }
        }

        _this.setData({
            chacao_a:resArr[0],
            chacao_b:resArr[1],
            chacao_c:resArr[2],
            chacao_d:resArr[3],
            chacao_e:resArr[4],
            chacao_f:resArr[5],
            chacao_g:resArr[6],
            chacao_h:resArr[7]
        })
    },
    doMainImgUrl:function(){
        var _this = this;
        let baseArr =['a','b','c','d','e','f','g'];
        let arr = _this.data.car[0];
        let resArr = [];
        
        for(var i = 0; i < baseArr.length; i++){
            if(arr[baseArr[i]] != ''){
                resArr.push(_this.data.baseImgUrl + '/parts/' + arr[baseArr[i]][0] + '/' + arr[baseArr[i]] + '_big.png');
            }else{
                resArr.push('');
            }
        }
        
        _this.setData({
            imgUrl_a:resArr[0],
            imgUrl_b:resArr[1],
            imgUrl_c:resArr[2],
            imgUrl_d:resArr[3],
            imgUrl_e:resArr[4],
            imgUrl_f:resArr[5],
            imgUrl_g:resArr[6]
        })
    },
    doScoreAnalysis: function (num) {
        if (num == '') return;
        //分析分数,获取车名
        var index = parseInt(num / 15000);
        if (index > 34) index = 34;
        var nameArr = ['SUV概念车', '越野一族', '商务座驾'];
        var arr = ['青铜级,lv1,level-qt.png', '青铜级,lv2,level-qt.png', '青铜级,lv3,level-qt.png', '青铜级,lv4,level-qt.png', '青铜级,lv5,level-qt.png',
            '白银级,lv1,level-by.png', '白银级,lv2,level-by.png', '白银级,lv3,level-by.png', '白银级,lv4,level-by.png', '白银级,lv5,level-by.png',
            '黄金级,lv1,level-hj.png', '黄金级,lv2,level-hj.png', '黄金级,lv3,level-hj.png', '黄金级,lv4,level-hj.png', '黄金级,lv5,level-hj.png',
            '铂金级,lv1,level-bj.png', '铂金级,lv2,level-bj.png', '铂金级,lv3,level-bj.png', '铂金级,lv4,level-bj.png', '铂金级,lv5,level-bj.png',
            '钻石级,lv1,level-zs.png', '钻石级,lv2,level-zs.png', '钻石级,lv3,level-zs.png', '钻石级,lv4,level-zs.png', '钻石级,lv5,level-zs.png',
            '大师级,lv1,level-ds.png', '大师级,lv2,level-ds.png', '大师级,lv3,level-ds.png', '大师级,lv4,level-ds.png', '大师级,lv5,level-ds.png',
            '王者级,lv1,level-wz.png', '王者级,lv2,level-wz.png', '王者级,lv3,level-wz.png', '王者级,lv4,level-wz.png', '王者级,lv5,level-wz.png'];

        var res = arr[index].split(',');

        this.setData({
            carRank: res[0],
            carLevel: res[1],
            carIconUrl: this.data.baseImgUrl + '/' + res[2]
        })
        if (this.data.carArrName == 0) return;
        // this.setData({
        //     carName: nameArr[this.data.carArrName - 1]
        // })
    },
    //前往改装车间
    toPartsPage:function(event){
        var act = event.target.dataset.name;

        wx.navigateTo({
            url:'../parts/parts?act=' + act
        })
    },
    toSharePage: function () {
      console.log(app.globalData)
        wx.navigateTo({
            url:'../share/share'
        });
    },
    //前往抽奖页面
    toLotteryPage: function () {
        var depot = app.globalData.depot;
        if (Object.keys(depot).length >= 48) {
          wx.showToast({
            title: '仓库已满,请先卖出多余配件',
            icon: 'none'
          })
          return false;
        }
        wx.navigateTo({
            url: '../lottery/lottery'
        })
    },
    //关闭按钮处理
    closeView: function (event) {
        var name = event.target.dataset.name;
        this.setData({
            [name]: false
        })
        if (event.target.id === 'intro') {
            wx.setStorage({
                key: 'intro',
                data: true
            })
        }
    },
    //打开按钮处理
    openView: function (event) {
        var name = event.target.dataset.name;
        this.setData({
            [name]: true
        })
    },
    choseCar: function (event) {
        var num = event.target.dataset.name;

        this.setData({
            choseCar: num
        })
    },
    noCarToast: function () {
        wx.showToast({
            title: "敬请期待",
            icon: 'none',
            duration: 1500
        })
    },
    getScore: function (str) {
        var baseAttribute = config.getBaseAttribute(str[0], str[1]);
        var colorAddition;
        if (str[0] == 'a' || str[0] == 'h') {
            colorAddition = 0;
        } else {
            colorAddition = config.getColorAddition(str[2]);
        }
        var res = config.getPartsScore(str[1], colorAddition, baseAttribute);
        return res
    },
    back: function () {
        //返回上一页
      wx.redirectTo({
        url: '../index/index'
      })
    }
})
